<?php
/*
  Microblog bot for game release notifications
  Copyright (C) 2017  Alexander Yakovlev

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace Source;

use \Game;

class IFDB extends Source {
  public $title = "IFDB";
  protected function parse() {
    $service = new \Sabre\Xml\Service();
    $xml = $this->get_text("http://ifdb.tads.org/allnew-rss");
    $service->elementMap = [
      '{}item' => function(\Sabre\Xml\Reader $reader) {
        $game = new Game;
        $keyValue = \Sabre\Xml\Deserializer\keyValue($reader, '{}item');
        if (isset($keyValue['{}title'])) {
          $title = $keyValue['{}title'];
          if (strpos($title, 'A new listing') === FALSE)
            return [];
          $title = str_replace('A new listing for ', '', $title);
          $title = explode(' by ', $title);
          $game->title = $title[0];
          $game->author = $title[1];
        }
        if (isset($keyValue['{}link'])) {
          $game->url = $keyValue['{}link'];
        }
        if (isset($keyValue['{}description'])) {
          $game->description = $keyValue['{}description'];
        }
        if (isset($keyValue['{}pubDate'])) {
          $game->date = strtotime($keyValue['{}pubDate']);
        }
        if ($game->date >= $this->period) {
          $this->games[] = $game;
        }
        return $game;
      },
    ];
    $dom = $service->parse($xml);
  }
}
